#include<iostream>
using namespace std;
class Complex
{
public:
    Complex(int r = 0, int i = 0) : mreal(r), mimage(i) { cout << "Complex(int,int)" << endl; }
    Complex(const Complex &src) { cout << "Complex(const Complex&)" << endl; }
    // 这里不能将Complex替换为Complex&，因为这里返回的对象是局部的，出了作用域就会被析构了
    Complex operator+(const Complex &src)
    {
        cout << "Complex operator+(const Complex &src)" << endl;
        // method 1 这里会产生一个对象，到时候会在调用这个函数的时候产生一个临时对象
        /*
        Complex comp;
        comp.mreal = this->mreal + src.mreal;
        comp.mimage = this->mimage + src.mimage;
        return comp;
        */
        // method 2 直接在调用这个函数的栈上生成临时对象，就不会在这里产生一个对象
        return Complex(this->mreal + src.mreal, this->mimage + src.mimage);
    }
    ~Complex() { cout << "~Complex()" << endl; }
    void show()
    {
        cout << "mreal:" << mreal << " mimage:" << mimage << endl;
    }
    // ++i前置++
    Complex& operator++()
    {
        mreal += 1;
        mimage += 1;
        return *this;
    }
    // i++后置++
    Complex operator++(int)
    {
        // Complex c = *this;
        // mreal += 1;
        // mimage += 1;
        // return *this;
        return Complex(mreal++, mimage++);
    }
    void operator+=(const Complex& src)
    {
        mreal += src.mreal;
        mimage = src.mimage;
    }

private:
    int mreal;
    int mimage;
    friend Complex operator+(const Complex &src1, const Complex &src2);//声明成友元函数就可以访问私有属性
    friend ostream &operator<<(ostream &out, const Complex &src);
    friend istream &operator>>(istream &in, Complex &src);
};

Complex operator+(const Complex& src1,const Complex& src2)
{
    cout << "Complex operator+(const Complex& src1,const Complex& src2)" << endl;
    return Complex(src1.mreal + src2.mreal, src1.mimage + src2.mimage);
}

ostream& operator<<(ostream& out,const Complex& src)
{
    out << "mreal:" << src.mreal << " mimage:" << src.mimage << endl;
    return out;
}
istream& operator>>(istream& in,Complex& src)
{
    in >> src.mreal >> src.mimage;
    return in;
}

int main()
{
    Complex c1(10, 10);
    Complex c2(20, 20);
    cout << "-----------" << endl;
    Complex c3 = c1 + c2;//c1+c2等价于c1.operator+(c2)，所以+操作符重载只有一个参数
    cout << "-----------" << endl;
    c3.show();
    Complex c4 = c3 + 20;//这里会将20进行转化成Complex类，调用构造函数
    c4.show();
    
    // 编译器做对象运算的时候，会调用对象的运算符重载函数（优先调用成员方法）
    // 如果没有成员方法，就在全局作用域找合适的运算符重载函数
    // Complex c5 = 30 + c4;//如果没有定义全局函数，这里会转化错误，没有办法将30转化为Complex
    Complex c5 = 30 + c4;//定义了全局的operator+后就能调用::operator+(30,c4)；
    c5.show();
    c5++;
    c5.show();

    cout << c5;
    /*
    ++/-- 表示自增运算符，也称为单目运算符  i++，++i怎么进行区分呢
    C++中将前置++i，利用operator++()表示；后置i++，利用operator++(int)表示；
    这样就构成了函数重载，实现了i++和++i分离
    */
    cin >> c5;
    cout << c5;
    return 0;
}